﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace ERF.Physics
{
    /// <summary>
    /// Represents damping logic. In other words, logic to 
    /// deaccelerate bodies moving on the ground.
    /// </summary>
    public class DampingLogic : PhysicsLogic
    {
        private const float MIN_VELOCITY_TRESHOLD = 0.01f;
        private float dampingFactor;
        /// <summary>
        /// Creates a new instance of DampingLogic with the given damping factor.
        /// </summary>
        /// <param name="dampingFactor">A value that denotes how much the velocity of an object will be scaled each update.</param>
        public DampingLogic(float dampingFactor)
        {
            this.dampingFactor = dampingFactor;
        }

        public override void ApplyOnBody(float timeSinceLastUpdate, Body body)
        {
            if (body.isOnGround && !body.isStatic)
            {
                // If the velocity is lower than a certain treshold, it is set to zero, to avoid scaling it 
                // until it reaches an infinitely small value.
                if (body.velocity.Length() < MIN_VELOCITY_TRESHOLD)
                    body.velocity = Vector3.Zero;
                else
                    body.velocity *= (dampingFactor * timeSinceLastUpdate);
            }
        }
    }
}
